#include "behaviourArbitrator.h"


void BehaviourArbitrator::eventTrigger(Event e)
{


}

ActionList* BehaviourArbitrator::update(StackI* _immediate, StackI* _shortTerm, StackI* _longTerm, EventList* _events, float _deltaSeconds, Character* _character)
{
	bool stateChanged = false;

	//Cleanup stacks of dead behaviours
	checkLifeOfStackBehaviours(_immediate);
	checkLifeOfStackBehaviours(_shortTerm);
	checkLifeOfStackBehaviours(_longTerm);


	if (_character->processEvents(_events, _immediate, _shortTerm, _longTerm))
	{
		stateChanged = true;
	}

	_events->emptyList();
		

	ActionList* newActions = NULL;

	if (!stateChanged)
	{
		if (!_immediate->isEmpty())
		{
			_immediate->peek()->update(_deltaSeconds);
		}
		else if (!_shortTerm->isEmpty())
		{
			_shortTerm->peek()->update(_deltaSeconds);
		}
		else if (!_longTerm->isEmpty())
		{
			_longTerm->peek()->update(_deltaSeconds);
		}
	}
	else
	{
		if (!_immediate->isEmpty())
		{
			newActions = _immediate->peek()->generateActions();
		}
		if (!_shortTerm->isEmpty())
		{
			newActions = _shortTerm->peek()->generateActions();
		}
		if (!_longTerm->isEmpty())
		{
			newActions = _longTerm->peek()->generateActions();
		}
	}


	return newActions;
}



Behaviour* BehaviourArbitrator::getCurrentBehaviour(StackI* _behaviourStack)
{
	if (!_behaviourStack->isEmpty())
		return _behaviourStack->peek();


	return NULL;
}

bool BehaviourArbitrator::checkLifeOfStackBehaviours(StackI* _behaviourStack)
{
	if (_behaviourStack->isEmpty())
		return false;

	bool removedItem = !_behaviourStack->peek()->isAliveActive();
	bool changeMade = removedItem;

	while (removedItem)
	{
		_behaviourStack->pop();

		if (_behaviourStack->isEmpty())
			return changeMade;

		removedItem = _behaviourStack->peek()->isAliveInactive();
	}

	return removedItem;
}